# -*- coding: utf-8 -*-
# !/usr/bin/env python
"""
-------------------------------------------------
   File Name：     ProxyManager.py  
   Description :  
   Author :       cherry
   date：          2017/5/23
   get/delete/refresh/get_all等接口的具体实现类，
-------------------------------------------------
   Change Activity:
                  2017/5/23
-------------------------------------------------
"""
from proxyManager.FreeProxyFactory import run as p_run
from refresh.SchedualTask import start
from multiprocessing import Process

__author__ = 'cherry'


from queue import Queue
import random


q = Queue() 
from db import DataBase as db



class ProxyManager(object):
    """
    ProxyManager
    """
    
    #初始化代理IP池的数据  从网站爬取IP 
    def __init__(self, *args, **kwargs):

        pass

        
            
    def get_one(self):
        """
        return a useful proxy
        :return: 随机返回一个代理IP池的一个可用代理IP
        """       
        return  str(db.select_one_proxy())
        

    def delete(self, proxyip):
        """
        delete proxy from pool
        :param proxy:  删除代理IP  先判断代理池中是否存在此IP 存在即删除  不存在返回False
        :return:
        """ 
        print (db.delete_proxy(proxyip))
       

         

    def getAll(self,size):
        """
        get all proxy from pool
                  获取到所有的代理IP池
        :return:
        """ 
        if size==0 or size==None:
            size=100
        return db.select_proxy_use(size)
    
    def refresh_ip_pool(self):
        """
                  刷新代理IP池
        :return:
        """
        p_list=[]
        p_list.append(Process(target=start, name='refresh_time'))
        '''#获取代理IP'''
        p_list.append(Process(target=p_run, name='p_run') )
        
        for p in p_list:
            p.start()
        for p in p_list:
            p.join()  
        return db.select_proxy_use()
    
